import {
	createRouter,
	createWebHistory,
	createWebHashHistory
} from "vue-router";
import homework from './homework.js'
import mode from './mode.js'
import word from './word.js'
import wrongRouter from './wrongRouter.js'
import phoneticPractice from './phoneticPractice.js'
import listeningRouter from './listening.js'
import followReading from './followReading.js'
import writtenTest from './writtenTest.js'
import phoneticSymbol from './phoneticSymbol.js'
import newConcept from './newConcept.js'
import brushWords from './brushWords.js'
import heibulin from './heibulin.js'
import textbookSync from './textbookSync.js'
import {
	showToast
} from "vant";

import store from '../store';

let routes = [{
		path: '/login',
		name: 'login',
		component: () => import('@/views/login/index.vue')
	},
	{
		path: '/',
		name: 'home',
		component: () => import('@/views/home/index.vue')
	},
	{
		path: '/home',
		name: 'home',
		component: () => import('@/views/home/index.vue')
	},
	...homework,
	...mode,
	...word,
	...wrongRouter,
	...phoneticPractice,
	...writtenTest,
	...phoneticSymbol,
	...listeningRouter,
	...newConcept,
	...heibulin,
	...brushWords,
	...followReading,
	...textbookSync
]
// 路由
const router = createRouter({
	history: createWebHashHistory(),
	routes
})
router.beforeEach((to, from, next) => {
	if (to.path === '/login') {
		next()
	} else if (to.query.token || to.fullPath.includes('token')) {
		localStorage.setItem('h5-token', to.fullPath.split('&').find(value => value.includes('token')).split(
			'=')[1])
		next()
	} else {
		const token = localStorage.getItem('h5-token')
		const userInfo = localStorage.getItem('userInfo')
		if (!token && (!userInfo || !userInfo.token)) {
			showToast('登录失效，请重新登录')
			next({
				name: 'login',
				redirect: '/login'
			})
		} else {
			userInfo && store.commit('setUserInfo', JSON.parse(userInfo));
			next()
		}
	}
})
// 导出
export default router